# encoding:utf8
'''
deloy web resources to remote by zip first
'''

import libappend
from py_lib import path_comp

import os
import sys
import shutil
from py_lib.remote import RemoteCtrl


REMOTE_CONFIG = dict(
    local=dict(
        UNAME="root",
        IP="192.168.62.144",
        PWD="123456",
    ),
    virtual=dict(
        UNAME="root",
        IP="45.32.84.116",
        PWD="k5$P}b)}_k5jbZcq",
    ),
)


class PackWeb:

    PATH_TEMPALTE = "TEMPLATE_"

    def __init__(self, spath, rconf):
        self._path_proj = spath
        self._path_temp = ""

        self._r_conf = rconf

    def __rm_tempalte(self):
        if os.path.isdir(self.PATH_TEMPALTE):
            shutil.rmtree(self.PATH_TEMPALTE)
        os.mkdir(self.PATH_TEMPALTE)
        self._path_temp = self.PATH_TEMPALTE

    def __archive_temp(self):
        ret = shutil.make_archive("web", "zip", root_dir=self._path_temp)
        shutil.rmtree(self._path_temp)
        return ret

    def __upload_web(self, zipf):
        (IP, UNAME,
         PWD) = self._r_conf["IP"], self._r_conf["UNAME"], self._r_conf["PWD"]
        cli = RemoteCtrl(IP, UNAME, PWD)
        zipfname = zipf.split(os.sep)[-1]
        OPENRESTY_STATIC = "/usr/local/openresty/nginx/html"
        cli.commit_file(
            zipf, "/usr/local/openresty/nginx/html/%s" % zipfname)
        ret = cli.ssh_command("cd %s &&  rm -r ./dist && rm -r ./res && unzip -o ./%s" %
                              (OPENRESTY_STATIC, zipfname))
        print(ret, '_____>>>ret')
        cli.close()

    def execute(self):
        self.__rm_tempalte()
        shutil.copytree("res", path_comp(self._path_temp + "/res"))
        shutil.copytree("dist", path_comp(self._path_temp + "/dist"))
        shutil.copy("index.html", self._path_temp)
        ret = self.__archive_temp()
        self.__upload_web(ret)


if __name__ == "__main__":
    if len(sys.argv) == 1:
        print("must in put rel type (local/virtual)")
        sys.exit()
    rtype = sys.argv[1]
    remote_conf = REMOTE_CONFIG[rtype]
    PROJ_PATH = os.path.abspath(path_comp("./../web/xpm"))
    os.chdir(PROJ_PATH)
    pw = PackWeb(PROJ_PATH, remote_conf)
    pw.execute()
